import time

from flask import Flask, request, jsonify
import subprocess
from flask_cors import CORS
import logging
import tempfile
import os
import uuid

app = Flask(__name__)
CORS(app)  # 启用 CORS

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 获取当前文件所在的目录
current_directory = os.path.dirname(os.path.abspath(__file__))
temp_directory = os.path.join(current_directory, 'temp')

# 确保 temp 目录存在
if not os.path.exists(temp_directory):
    os.makedirs(temp_directory)

@app.route('/', methods=['GET'])
def index():
    return jsonify({'message': 'Hello, World!'})

@app.route('/run_python', methods=['POST'])
def run_python():
    try:
        code = request.json['code']
        logger.info(f"Received code: {code}")
        # 删除目录下一小时前的文件
        for file in os.listdir(temp_directory):
            file_path = os.path.join(temp_directory, file)
            if os.path.isfile(file_path):
                if os.path.getmtime(file_path) < time.time() - 3600:
                    os.remove(file_path)

        # 创建一个随机的文件名
        random_filename = f"{uuid.uuid4().hex}.py"
        temp_file_path = os.path.join(temp_directory, random_filename)

        # 将代码写入临时文件
        with open(temp_file_path, 'w', encoding='utf-8') as temp:
            temp.write(code)
            temp.flush()  # 确保文件内容被写入磁盘

        # 执行 Python 代码
        result = subprocess.run(['python', temp_file_path], capture_output=True, text=True,encoding='utf-8')
        output = result.stdout + result.stderr

        # 删除临时文件
        os.remove(temp_file_path)

        logger.info(f"Execution output: {output}")
        return jsonify({'output': output})

    except KeyError as e:
        logger.error(f"Missing key in request: {e}")
        return jsonify({'error': 'Invalid request format'}), 400

    except subprocess.CalledProcessError as e:
        logger.error(f"Subprocess error: {e}")
        return jsonify({'error': f'Execution failed: {e.stderr}'}), 500

    except Exception as e:
        logger.error(f"Unexpected error: {e}")
        return jsonify({'error': 'Internal server error'}), 500

if __name__ == '__main__':
    app.run(debug=True,host='0.0.0.0', port=5000)